package com.bwc.aidemo.util

import com.google.gson.Gson
import com.google.gson.reflect.TypeToken
import com.tencent.mmkv.MMKV

/**
 * 本地存储
 */
object MMKVUtil {
     val mmkv: MMKV = MMKV.defaultMMKV()
     val gson: Gson = Gson()

    // 存储数据的方法
    fun put(key: String, value: Any) {
        when (value) {
            is String -> mmkv.encode(key, value)
            is Int -> mmkv.encode(key, value)
            is Long -> mmkv.encode(key, value)
            is Float -> mmkv.encode(key, value)
            is Boolean -> mmkv.encode(key, value)
            is Double -> mmkv.encode(key, value)
            is ByteArray -> mmkv.encode(key, value)
            else -> {
                // 使用 Gson 序列化对象为 JSON 字符串
                val json = gson.toJson(value)
                mmkv.encode(key, json)
            }
        }
    }

    // 获取数据的方法
    inline fun <reified T> get(key: String, defaultValue: T): T {
        return when (defaultValue) {
            is String -> mmkv.decodeString(key, defaultValue) as T
            is Int -> mmkv.decodeInt(key, defaultValue) as T
            is Long -> mmkv.decodeLong(key, defaultValue) as T
            is Float -> mmkv.decodeFloat(key, defaultValue) as T
            is Boolean -> mmkv.decodeBool(key, defaultValue) as T
            is Double -> mmkv.decodeDouble(key, defaultValue) as T
            is ByteArray -> (mmkv.decodeBytes(key) ?: defaultValue) as T
            else -> {
                val json = mmkv.decodeString(key, null)
                if (!json.isNullOrEmpty()) {
                    val type = object : TypeToken<T>() {}.type
                    gson.fromJson<T>(json, type)
                } else defaultValue
            }
        }
    }


    // 删除指定 key
    fun remove(key: String) {
        mmkv.removeValueForKey(key)
    }

    // 清除所有数据
    fun clear() {
        mmkv.clearAll()
    }
}